package com.glx.test.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.glx.test.utils.JsonUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/AI")
public class DeepSeekController {

    @Value("${deepseek.api.key}")
    private String apiKey;
    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final ExecutorService executor = Executors.newCachedThreadPool();

    @GetMapping(value = "/stream-chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(@RequestParam String question) {
        SseEmitter emitter = new SseEmitter(-1L);
        executor.execute(() -> {
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost request = new HttpPost(apiUrl);
                request.setHeader("Authorization", "Bearer " + apiKey);
                request.setHeader("Content-Type", "application/json");

                // 构建流式请求体
                String requestBody = JsonUtils.buildJsonBody(question,"");
                request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));

                // 处理流式响应
                try (CloseableHttpResponse response = client.execute(request);
                     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring(6);
                            if ("[DONE]".equals(data)) {
                                emitter.send(SseEmitter.event().data("[DONE]"));
                                break;
                            }
                            String content = new ObjectMapper().readTree(data)
                                    .path("choices").get(0).path("delta").path("content").asText();
                            if (!content.isEmpty()) {
                                emitter.send(content);
                            }
                        }
                    }
                    emitter.complete();
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }

}
